require.config({
    paths: {
        'jquery': ['http://cdn.bootcss.com/jquery/2.2.4/jquery.min', '/js/lib/jquery.min'],
        'doT': '/js/lib/doT.min',
        'bootstrap': '/js/lib/bootstrap.min',
        'datetimepicker': '/js/lib/bootstrap-datetimepicker.min',
        'select2': '/js/lib/select2.min',
        'paginator': '/js/lib/bootstrap-paginator'
    },
    shim: {
        'bootstrap': ['jquery'],
        'paginator': ['bootstrap']
    }
});

var myFun = {};

require(['jquery', 'doT', 'datetimepicker', 'select2', 'paginator', 'common', 'bootstrap'], function($, doT, datetimepicker, select2, paginator, common) {
    $(function() {
        var role = sessionStorage.getItem('role');
        var school_id = sessionStorage.getItem('school_id');
        var page_size = 10;
        $('#goodsInfo').hide();

        function initDatetimepicker() {
            var date = new Date();
            var date_string = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            $('.goods_date').datetimepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                maxView: 'decade',
                minView: 'month',
                endDate: date
            });
            $('.goods_time').datetimepicker({
                format: 'hh:ii:ss',
                autoclose: true,
                startView: 1,
                maxView: 'day',
                minView: 'hour',
                minuteStep: 1,
                title: date_string
            });

            $('#goodsdateStart').val(date_string);
            $('#goodsdateEnd').val(date_string);
            $('#timeStart').val('00:00:00');
            $('#timeEnd').val('23:59:59');
        }
        initDatetimepicker();

        //初始化学校列表
        function initSchool() {
            var data;
            $.get(common.urlBase + "/school/allSchool.json", function(data, status) {
                data = eval('(' + data + ')');
                var all = { "id": "-1", "name": "全部" };
                var schools = data.data;
                schools.unshift(all);
                var schoolTmpl = doT.template($('#template_school').text());
                $('#querySchool').html(schoolTmpl(schools));
                $("#querySchool").select2();
                getCanteen($('#querySchool').val());
                if (role != 1) {
                    $('#querySchool').attr('disabled', true);
                    $('#querySchool').val(school_id);
                    $('#select2-querySchool-container').text($('#querySchool option[value=' + school_id + ']').text());

                }
            });



        }
        initSchool();

        $('#querySchool').on('change', function() {
            var school_id = $('#querySchool').val();
            console.log(school_id);
            getCanteen(school_id);
        });

        function getCanteen(school_id) {
            var canteenTmpl = doT.template($('#template_canteen').text());
            var canteen_zero = [{ 'id': 'zero', 'name': '无食堂' }];
            var canteen_all = { 'id': -1, 'name': '全部' };
            if (school_id == -1) {
                $.get(common.urlBase + '/shop/getAllShop/getAllShop.json', function(data, statu) {
                    data = eval('(' + data + ')');
                    if (data['ok']) {
                        data.data.unshift(canteen_all);
                        $('#canteens').html(canteenTmpl(data.data));
                        $("#canteens").select2();
                    } else {
                        $('#noticeMsg').text(data['message']);
                        $('#noticeModal').modal('show');
                        $('#canteens').html(canteenTmpl(canteen_zero));
                    }
                });
            } else {
                $.get(common.urlBase + '/shop/school-shop/' + school_id + '.json', function(data, statu) {
                    data = eval('(' + data + ')');
                    if (data['ok']) {
                        $('#canteens').html(canteenTmpl(data.data));
                        $("#canteens").select2();
                    } else {

                        $('#canteens').html(canteenTmpl(canteen_zero));
                        $('#noticeMsg').text(data['message']);
                        $('#noticeModal').modal('show');
                    }
                });
            }
            
        }


        //用从数据库获得的信息填充商品条目信息

        function getGoods(page, page_size) {
            myFun.data.page_no = page;
            myFun.data.page_size = page_size;

            $.get(common.urlBase + '/item/query/sales/' + myFun.shop_id + '.json', myFun.data, function(data, statu) {
                data = eval('(' + data + ')');
                var goodsTmpl = doT.template($('#template_goods').text());
                var total = data.data.total_result;
                console.log(data.data.obj[0]);
                if (total) {
                    $('#goods').html(goodsTmpl(data.data.obj));
                    $('#total').text(total);
                    var pageNumber = Math.ceil(total / page_size);
                    initPaginator(page, 8, pageNumber);
                    $('#goodsInfo').show();
                } else {
                    $('#noticeMsg').text('无相关信息！');
                    $('#noticeModal').modal('show');
                    $('#goodsInfo').hide();
                }
            });
        }

        //获取表单的信息,链接数据库
        $('#goodsForm').submit(function() {
            var school = $('#querySchool').val();
            var canteen = $('#canteens').val();
            var start_time = Date.parse($('#goodsdateStart').val() + ' ' + $('#timeStart').val());
            var end_time = Date.parse($('#goodsdateEnd').val() + ' ' + $('#timeEnd').val());

            if (start_time >= end_time) {
                $('#tips').text('请选择正确的日期！');
                return false;
            } else {
                $('#tips').text('');
            }

            myFun.shop_id = canteen;
            myFun.data = {
                'start_time': start_time,
                'end_time': end_time
            };

            refreshGoods(1);

            return false;
        });

        function refreshGoods(page) {
            getGoods(page, page_size);
        }

        function initPaginator(currentPage, numberOfPages, totalPages) {
            var options = {
                currentPage: currentPage,
                numberOfPages: numberOfPages,
                totalPages: totalPages,
                itemTexts: function(type, page, current) {
                    switch (type) {
                        case 'first':
                            return '首页';
                        case 'prev':
                            return '上一页';
                        case 'next':
                            return '下一页';
                        case 'last':
                            return '末页';
                        case 'page':
                            return page;

                    }
                },
                onPageChanged: function(event, oldPage, newPage) {
                    refreshGoods(newPage);
                }
            };
            $('#paginator').bootstrapPaginator(options);
        }
    });

});
